package com.coder520.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lilipo on 2018/2/4.
 */
@Controller
@RequestMapping("hello")
public class HelloController {
    @RequestMapping("/say")
    @ResponseBody
    public Map say(ModelMap modelMap){
        Map<String, String> map = new HashMap<>();
        map.put("aaa","AAA1111111");
        map.put("bbb","BBB");
        modelMap.addAttribute("map",map);
        return map;
    }
    @RequestMapping("/say2")
    public String say2(){
        return "say";
    }
    @RequestMapping("/up")
    public String up( @RequestParam("file") MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        file.transferTo(new File("D:/", filename));
        return "say";
    }

    @RequestMapping("/down")
    public ResponseEntity<byte[]> down() throws IOException {
        File file=new File("d:/zz.txt");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",file.getName());
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.set("characterEncoding","utf-8");
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
}
